import { login, getUserProfile, getUserDetailById } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 更新token
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    // 删除token
    delToken(state) {
      state.token = ''
      removeToken() // 删除本地token
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, data) {
      console.log('action userLogin', context, data)
      const res = await login(data)
      // token存在vuex 中
      context.commit('updateToken', res.data)
    },
    async getUserProfile(context) {
      const res = await getUserProfile()
      console.log('获取用户基本资料', res)
      const info = await getUserDetailById(res.data.userId)
      console.log('获取用户详细信息', info.data)
      context.commit('setUserInfo', { ...res.data, ...info.data })
    },
    logout(context, data) {
      context.commit('delToken')
      context.commit('reomveUserInfo')
    }
  }
}
